<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>图片上传测试</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { padding: 50px; font-family: Arial, sans-serif; }
        .container { max-width: 800px; margin: 0 auto; }
        .upload-box { border: 2px dashed #ccc; padding: 30px; text-align: center; margin-bottom: 30px; cursor: pointer; }
        .upload-box:hover { border-color: #007bff; }
        #fileInput { display: none; }
        .btn { padding: 10px 20px; background: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        .btn:hover { background: #0056b3; }
        .file-list { margin: 20px 0; }
        .file-item { padding: 10px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; }
        .result { margin-top: 20px; padding: 15px; border-radius: 4px; display: none; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <div class="container">
        <h1>图片上传测试（最多8张）</h1>
        
        <!-- 上传区域 -->
        <div class="upload-box" id="uploadBox">
            <input type="file" id="fileInput" accept="image/*" multiple>
            <h3>点击或拖拽图片到此处上传</h3>
            <p>支持格式：bmp、dib、pcp、dif、wmf、gif、jpg、jpeg、tif、eps、psd、cdr、iff、tga、pcd、mpt、png</p>
        </div>
        
        <!-- 已选择文件列表 -->
        <div class="file-list" id="fileList"></div>
        
        <!-- 上传按钮 -->
        <button class="btn" id="uploadBtn" disabled>上传选中文件</button>
        
        <!-- 上传结果 -->
        <div class="result" id="result"></div>
    </div>

    <script>
        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const uploadBox = document.getElementById('uploadBox');
        const fileList = document.getElementById('fileList');
        const uploadBtn = document.getElementById('uploadBtn');
        const result = document.getElementById('result');

        let selectedFiles = []; // 选中的文件列表

        // 点击上传区域触发文件选择
        uploadBox.addEventListener('click', () => fileInput.click());

        // 拖拽文件到上传区域
        uploadBox.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadBox.style.borderColor = '#007bff';
        });
        uploadBox.addEventListener('dragleave', () => {
            uploadBox.style.borderColor = '#ccc';
        });
        uploadBox.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadBox.style.borderColor = '#ccc';
            if (e.dataTransfer.files.length > 0) {
                handleFiles(e.dataTransfer.files);
            }
        });

        // 选择文件后处理
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        // 处理选中的文件
        function handleFiles(files) {
            // 清空之前的选择（可选：改为追加则注释此行）
            selectedFiles = [];
            fileList.innerHTML = '';

            // 限制最多8张
            const maxCount = 8;
            const validFiles = Array.from(files).filter(file => {
                const ext = file.name.split('.').pop().toLowerCase();
                const supportExts = ['bmp', 'dib', 'pcp', 'dif', 'wmf', 'gif', 'jpg', 'jpeg', 'tif', 'eps', 'psd', 'cdr', 'iff', 'tga', 'pcd', 'mpt', 'png'];
                return supportExts.includes(ext);
            });

            if (validFiles.length > maxCount) {
                showResult(`最多只能选择8张图片，已自动过滤超出部分`, 'error');
                selectedFiles = validFiles.slice(0, maxCount);
            } else {
                selectedFiles = validFiles;
            }

            // 显示选中的文件
            selectedFiles.forEach((file, index) => {
                const fileSize = (file.size / 1024).toFixed(2) + 'KB';
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <span>${index + 1}. ${file.name}（${fileSize}）</span>
                    <button class="btn" style="background: #dc3545; padding: 5px 10px;" onclick="removeFile(${index})">删除</button>
                `;
                fileList.appendChild(fileItem);
            });

            // 启用/禁用上传按钮
            uploadBtn.disabled = selectedFiles.length === 0;
        }

        // 删除选中的文件
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            fileList.innerHTML = '';
            selectedFiles.forEach((file, i) => {
                const fileSize = (file.size / 1024).toFixed(2) + 'KB';
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <span>${i + 1}. ${file.name}（${fileSize}）</span>
                    <button class="btn" style="background: #dc3545; padding: 5px 10px;" onclick="removeFile(${i})">删除</button>
                `;
                fileList.appendChild(fileItem);
            });
            uploadBtn.disabled = selectedFiles.length === 0;
        }

        // 上传文件到后端接口
        uploadBtn.addEventListener('click', async () => {
            if (selectedFiles.length === 0) return;

            // 创建FormData
            const formData = new FormData();
            selectedFiles.forEach(file => {
                formData.append('files', file); // 参数名与接口@RequestParam一致
            });

            try {
                // 发送上传请求（替换为你的接口地址）
                const response = await fetch('http://localhost:8181/upload/pic', {
                    method: 'POST',
                    body: formData,
                    // 跨域场景需添加：credentials: 'include'
                });

                const resData = await response.json();

                // 显示结果
                if (resData.code === 0) {
                    let resultHtml = `<h4>上传成功！</h4>`;
                    resData.data.forEach((file, index) => {
                        resultHtml += `<p>${index + 1}. ${file.fileName} - 大小：${file.fileSize}B - 访问地址：${file.url}</p>`;
                    });
                    showResult(resultHtml, 'success');

                    // 上传成功后清空选择
                    selectedFiles = [];
                    fileList.innerHTML = '';
                    uploadBtn.disabled = true;
                } else {
                    showResult(`上传失败：${resData.msg}`, 'error');
                }
            } catch (error) {
                showResult(`网络错误：${error.message}`, 'error');
            }
        });

        // 显示结果提示
        function showResult(msg, type) {
            result.innerHTML = msg;
            result.className = `result ${type}`;
            result.style.display = 'block';

            // 3秒后自动隐藏（可选）
            setTimeout(() => {
                result.style.display = 'none';
            }, 5000);
        }
    </script>
</body>
</html>